<template>
  <view class="auth-stats-container">
    <z-paging 
      ref="paging" 
      v-model="dataList" 
      @query="queryList"
      :auto="false"
      :refresher-enabled="true"
      :loading-more-enabled="true"
      :empty-view-text="'暂无数据'"
      class="list-paging"
    >
      <template #top>
        <!-- 页面标题 -->
        <view class="page-header">
          <view class="header-title">认证统计</view>
        </view>
        
        <!-- 筛选区域 -->
        <view class="filter-section">
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">统计周期：</text>
              <picker mode="selector" :value="filters.periodIndex" :range="periodOptions" @change="onPeriodChange">
                <view class="date-picker">
                  <text>{{ filters.periodIndex >= 0 ? periodOptions[filters.periodIndex] : '请选择' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
            
            <view class="filter-item">
               <text class="filter-label">认证类型：</text>
               <picker :value="filters.authTypeIndex" :range="authTypes.map(item => item.name)" @change="onAuthTypeChange">
                  <view class="date-picker">
                   <text>{{ filters.authTypeIndex >= 0 ? authTypes[filters.authTypeIndex].name : '全部' }}</text>
                   <up-icon name="arrow-down" size="14"></up-icon>
                  </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-actions">
            <button class="search-btn" @click="searchData">查询</button>
            <button class="reset-btn" @click="resetFilters">重置</button>
          </view>
        </view>
        
        <!-- 统计摘要 -->
        <view class="summary-section">
          <view class="summary-card">
            <view class="summary-title">认证总数</view>
            <view class="summary-value">{{ summary.totalCount }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">通过数量</view>
            <view class="summary-value">{{ summary.passedCount }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">通过率</view>
            <view class="summary-value">{{ summary.passRate }}</view>
          </view>
        </view>
        
        <!-- 列表表头 -->
        <view class="list-header">
          <text class="list-cell">认证类型</text>
          <text class="list-cell">认证数量</text>
          <text class="list-cell">通过数量</text>
          <text class="list-cell">通过率</text>
        </view>
      </template>
      
      <!-- 列表内容 -->
      <view v-for="(item, index) in dataList" :key="index" class="list-row" @click="openDetail(item)">
        <view class="list-cell transaction-cell">
          <view class="transaction-tag auth-tag" :class="getTagClass(item.authTypeValue)">
            {{ item.authTypeName }}
          </view>
        </view>
        <text class="list-cell">{{ item.totalCount }}次</text>
        <text class="list-cell">{{ item.passedCount }}次</text>
        <text class="list-cell">{{ item.passRate }}</text>
      </view>
    </z-paging>
    
    <!-- 详情弹窗 -->
    <view class="detail-modal" v-if="showDetailModal">
      <view class="detail-content">
        <view class="detail-header">
          <text class="detail-title">{{ currentDetail ? currentDetail.authTypeName + ' 详情' : '详情信息' }}</text>
          <text class="close-btn" @click="showDetailModal = false">×</text>
        </view>
        
        <view class="detail-body" v-if="currentDetail">
          <view class="detail-item">
            <text class="detail-label">认证类型：</text>
            <view class="detail-value">
              <view class="transaction-tag auth-tag" :class="getTagClass(currentDetail.authTypeValue)">
                {{ currentDetail.authTypeName }}
              </view>
            </view>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">统计周期：</text>
            <text class="detail-value">{{ periodOptions[filters.periodIndex] }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">认证总数：</text>
            <text class="detail-value">{{ currentDetail.totalCount }}次</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">通过数量：</text>
            <text class="detail-value">{{ currentDetail.passedCount }}次</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">拒绝数量：</text>
            <text class="detail-value">{{ currentDetail.rejectedCount }}次</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">通过率：</text>
            <text class="detail-value">{{ currentDetail.passRate }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">平均审核时长：</text>
            <text class="detail-value">{{ currentDetail.avgReviewTime }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">最长审核时长：</text>
            <text class="detail-value">{{ currentDetail.maxReviewTime }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">最短审核时长：</text>
            <text class="detail-value">{{ currentDetail.minReviewTime }}</text>
          </view>
          
          <view class="detail-item" v-if="currentDetail.timeDistribution && currentDetail.timeDistribution.length > 0">
            <text class="detail-label">时段分布：</text>
            <view class="detail-value">
              <view v-for="(time, idx) in currentDetail.timeDistribution" :key="idx" class="time-item">
                {{ time.name }}: {{ time.count }}次 ({{ time.percentage }}%)
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'

// 筛选表单
const filters = reactive({
  periodIndex: 0,
  authTypeIndex: -1
})

// 统计周期选项
const periodOptions = [
  '日统计',
  '月统计',
  '年统计'
]

// 认证类型
const authTypes = [
  { name: '全部', value: 'all' },
  { name: '实名认证', value: 'real_name' },
  { name: '车辆认证', value: 'vehicle' },
  { name: '企业认证', value: 'enterprise' },
  { name: '驾驶证认证', value: 'driver_license' }
]

// 列表数据
const dataList = ref([])
const paging = ref(null)

// 统计摘要数据
const summary = reactive({
  totalCount: '0次',
  passedCount: '0次',
  passRate: '0%'
})

// 详情弹窗
const showDetailModal = ref(false)
const currentDetail = ref(null)

// 获取标签样式类
const getTagClass = (type) => {
  switch(type) {
    case 'real_name':
      return 'real-name-tag'
    case 'vehicle':
      return 'vehicle-tag'
    case 'enterprise':
      return 'enterprise-tag'
    case 'driver_license':
      return 'driver-license-tag'
    default:
      return ''
  }
}

// 统计周期选择处理
const onPeriodChange = (e) => {
  filters.periodIndex = parseInt(e.detail.value)
}

// 认证类型选择处理
const onAuthTypeChange = (e) => {
  filters.authTypeIndex = parseInt(e.detail.value)
}

// 查询数据
const searchData = () => {
  if (paging.value) {
    paging.value.reload()
  }
}

// 重置筛选条件
const resetFilters = () => {
  filters.periodIndex = 0
  filters.authTypeIndex = -1
  
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
}

// 查询列表数据
const queryList = (pageNo, pageSize) => {
  // 模拟请求延迟
  setTimeout(() => {
    // 生成模拟数据
    const data = generateMockData(pageNo, pageSize)
    paging.value.complete(data)
    
    // 更新统计摘要
    updateSummary(data)
  }, 500)
}

// 更新统计摘要
const updateSummary = (data) => {
  // 计算总认证数、总通过数和通过率
  let totalCount = 0
  let totalPassedCount = 0
  
  data.forEach(item => {
    totalCount += item.totalCount
    totalPassedCount += item.passedCount
  })
  
  // 计算通过率
  const passRate = totalCount > 0 ? ((totalPassedCount / totalCount) * 100).toFixed(2) + '%' : '0%'
  
  // 更新摘要数据
  summary.totalCount = totalCount + '次'
  summary.passedCount = totalPassedCount + '次'
  summary.passRate = passRate
}

// 生成模拟数据
const generateMockData = (pageNo, pageSize) => {
  const data = []
  
  // 时段分布
  const timeDistributions = [
    { name: '早上(6:00-10:00)', value: 'morning' },
    { name: '中午(10:00-14:00)', value: 'noon' },
    { name: '下午(14:00-18:00)', value: 'afternoon' },
    { name: '晚上(18:00-22:00)', value: 'evening' },
    { name: '深夜(22:00-6:00)', value: 'night' }
  ]
  
  // 筛选认证类型
  let filteredAuthTypes = [...authTypes.slice(1)] // 排除'全部'选项
  if (filters.authTypeIndex > 0) { // 0是全部，大于0才需要筛选
    filteredAuthTypes = [authTypes[filters.authTypeIndex]]
  }
  
  // 计算总认证次数（用于计算占比）
  const totalAuthCount = Math.floor(Math.random() * 500) + 100 // 100-600次
  
  // 生成随机数据
  for (const authType of filteredAuthTypes) {
    // 根据认证类型设置不同的分布
    let countPercentage, passRatePercentage
    
    if (authType.value === 'real_name') {
      countPercentage = Math.random() * 0.2 + 0.3 // 30%-50%
      passRatePercentage = Math.random() * 0.1 + 0.85 // 85%-95%
    } else if (authType.value === 'vehicle') {
      countPercentage = Math.random() * 0.2 + 0.2 // 20%-40%
      passRatePercentage = Math.random() * 0.15 + 0.75 // 75%-90%
    } else if (authType.value === 'enterprise') {
      countPercentage = Math.random() * 0.1 + 0.1 // 10%-20%
      passRatePercentage = Math.random() * 0.2 + 0.7 // 70%-90%
    } else {
      countPercentage = Math.random() * 0.1 + 0.1 // 10%-20%
      passRatePercentage = Math.random() * 0.15 + 0.8 // 80%-95%
    }
    
    const totalCount = Math.floor(totalAuthCount * countPercentage)
    const passedCount = Math.floor(totalCount * passRatePercentage)
    const rejectedCount = totalCount - passedCount
    const passRate = ((passedCount / totalCount) * 100).toFixed(2) + '%'
    
    // 审核时长（分钟）
    const avgReviewTime = Math.floor(Math.random() * 60) + 30 // 30-90分钟
    const maxReviewTime = avgReviewTime * (Math.random() * 1 + 1.5) // 平均值的1.5-2.5倍
    const minReviewTime = avgReviewTime * (Math.random() * 0.3 + 0.2) // 平均值的0.2-0.5倍
    
    // 生成时段分布
    const timeDistribution = []
    let remainingCount = totalCount
    
    for (let i = 0; i < timeDistributions.length; i++) {
      const isLast = i === timeDistributions.length - 1
      const timeCount = isLast ? remainingCount : Math.floor(remainingCount * (Math.random() * 0.4 + 0.1)) // 10%-50%
      
      if (timeCount > 0) {
        const timePercentage = ((timeCount / totalCount) * 100).toFixed(2)
        
        timeDistribution.push({
          name: timeDistributions[i].name,
          count: timeCount,
          percentage: timePercentage
        })
        
        remainingCount -= timeCount
      }
      
      if (remainingCount <= 0) break
    }
    
    // 添加数据
    data.push({
      authTypeName: authType.name,
      authTypeValue: authType.value,
      totalCount,
      passedCount,
      rejectedCount,
      passRate,
      avgReviewTime: avgReviewTime + '分钟',
      maxReviewTime: Math.floor(maxReviewTime) + '分钟',
      minReviewTime: Math.floor(minReviewTime) + '分钟',
      timeDistribution
    })
  }
  
  // 按认证次数排序
  return data.sort((a, b) => b.totalCount - a.totalCount)
}

// 打开详情弹窗
const openDetail = (item) => {
  currentDetail.value = item
  showDetailModal.value = true
}

// 页面加载时查询数据
onMounted(() => {
  searchData()
})
</script>

<style lang="scss" scoped>
.auth-stats-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.list-paging {
  height: 100%;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
  }
}

.filter-section {
  background-color: white;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .filter-row {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 20rpx;
  }
  
  .filter-item {
    flex: 1;
    min-width: 300rpx;
    margin-bottom: 10rpx;
    display: flex;
    align-items: center;
    
    .filter-label {
      font-size: 28rpx;
      color: #333;
      margin-right: 10rpx;
      white-space: nowrap;
    }
    
    .date-picker {
      flex: 1;
      height: 60rpx;
      border: 1px solid #ddd;
      border-radius: 6rpx;
      padding: 0 20rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 28rpx;
    }
  }
  
  .filter-actions {
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
    
    button {
      min-width: 160rpx;
      height: 70rpx;
      line-height: 70rpx;
      font-size: 28rpx;
      margin: 0;
      padding: 0 30rpx;
    }
    
    .search-btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }
    
    .reset-btn {
      background-color: #f5f5f5;
      color: #666;
    }
  }
}

.summary-section {
  display: flex;
  justify-content: space-between;
  padding: 0 20rpx;
  margin-bottom: 20rpx;
  
  .summary-card {
    flex: 1;
    background-color: white;
    border-radius: 10rpx;
    padding: 20rpx;
    margin: 0 10rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    text-align: center;
    
    .summary-title {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
    }
    
    .summary-value {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }
}

.list-header {
  display: flex;
  background-color: #f8f8f8;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #666;
  font-weight: bold;
  border-bottom: 1px solid #eee;
}

.list-row {
  display: flex;
  background-color: white;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1px solid #f5f5f5;
}

.list-cell {
  flex: 1;
  display: flex;
  align-items: center;
}

.transaction-cell {
  display: flex;
  align-items: center;
}

.transaction-tag {
  padding: 6rpx 16rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  color: white;
}

.auth-tag {
  background-color: #4CAF50;
}

.real-name-tag {
  background-color: #2196F3;
}

.vehicle-tag {
  background-color: #FF9800;
}

.enterprise-tag {
  background-color: #9C27B0;
}

.driver-license-tag {
  background-color: #F44336;
}

.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.detail-content {
  width: 80%;
  max-height: 80%;
  background-color: white;
  border-radius: 10rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.detail-header {
  padding: 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .detail-title {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .close-btn {
    font-size: 40rpx;
    line-height: 1;
  }
}

.detail-body {
  padding: 30rpx;
  overflow-y: auto;
  flex: 1;
  
  .detail-item {
    margin-bottom: 20rpx;
    display: flex;
    
    .detail-label {
      width: 200rpx;
      font-size: 28rpx;
      color: #666;
    }
    
    .detail-value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
    
    .time-item {
      margin-bottom: 10rpx;
    }
  }
}
</style>